package cn.highedu.coolsharkhub.service.impl;

import cn.highedu.coolsharkhub.entity.Banner;
import cn.highedu.coolsharkhub.entity.dto.BannerDTO;
import cn.highedu.coolsharkhub.entity.vo.BannerHomepageVO;
import cn.highedu.coolsharkhub.entity.vo.BannerManagementVO;
import cn.highedu.coolsharkhub.mapper.BannerMapper;
import cn.highedu.coolsharkhub.service.BannerService;
import cn.highedu.coolsharkhub.service.exception.BlankParameterException;
import cn.highedu.coolsharkhub.service.exception.EntityNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 轮播图业务层实现类
 */
@Service
public class BannerServiceImpl implements BannerService {
    Logger logger = LoggerFactory.getLogger(BannerServiceImpl.class);
    @Autowired
    BannerMapper bannerMapper;
    /**
     * 后台管理查询所有轮播图
     * @return 所有轮播图
     */
    @Override
    public List<BannerManagementVO> findAll() {
        List<Banner> banners = bannerMapper.selectAll();
        List<BannerManagementVO> bannerManagementVOS = new ArrayList<>();
        banners.forEach(banner -> {
            BannerManagementVO bannerManagementVO = new BannerManagementVO();
            bannerManagementVO.setId(banner.getId());
            bannerManagementVO.setUrl(banner.getUrl());
            bannerManagementVO.setSort(banner.getSort());
            bannerManagementVOS.add(bannerManagementVO);
        });
        return bannerManagementVOS;
    }

    /**
     * 保存轮播图
     *
     * @param bannerDTO 轮播图数据
     */
    @Override
    public void addBanner(BannerDTO bannerDTO) {
        if (bannerDTO == null) {
            throw new BlankParameterException("轮播图信息不能为空");
        }
        if (bannerDTO.getUrl() == null || bannerDTO.getUrl().isEmpty()) {
            throw new BlankParameterException("轮播图路径不能为空");
        }
        // 创建Banner实体类对象
        Banner banner = new Banner(null, bannerDTO.getUrl(), bannerDTO.getSort());
        // 保存Banner实体类对象
        int rows = bannerMapper.insert(banner);
        if (rows == 1) {
            logger.info("保存轮播图成功: {}", rows);
        }
        else {
            throw new EntityNotFoundException("保存轮播图失败");
        }
    }

    /**
     * 查询所有轮播图 用于前台页面显示轮播图
     * @return 所有轮播图
     */
    @Override
    public List<BannerHomepageVO> findAllForHomepage() {
        return bannerMapper.findAllForHomepage();
    }
}
